<?php
require_once('config.php');

$query="SELECT p_name, c_name, Race.name AS race, Align.name AS align, Relign.name AS relig, str, dex, con, wis, cha, gp, fort_save, ref_save, will_save, `int`, lvl, base_attack_bonus AS bab, hp, lvl, exp
FROM Player
INNER JOIN Race ON Race.race_id = Player.race_id
INNER JOIN Align ON Align.align_id = Player.align_id
INNER JOIN Relign ON Relign.relign_id = Player.relign_id
WHERE Player.player_id=".$_GET["pid"];
$res=mysql_query($query);
$base=mysql_fetch_assoc($res);

$modifier=-4;
for ($i=2; $i<40; $i=$i+2){
	$att_bonus[$i]=$modifier;
	$att_bonus[$i+1]=$modifier;
	$modifier++;
}

$query="SELECT amount, name, Equip.value, equip_type_id AS type, Bonus.value AS hitbonus, Bonus.damage AS damagebonus FROM P_Equip INNER JOIN Equip ON P_Equip.equip_id=Equip.equip_id LEFT JOIN Bonus on Bonus.bonus_id=P_Equip.bonus_id WHERE player_id=".$_GET['pid']." ORDER BY type, name";
$res=mysql_query($query);
echo mysql_error();
$weapons=array();
$eq=array();
while ($item=mysql_fetch_assoc($res)){
	if (intval($item['type'])==1){
		array_push($weapons, $item);
	}
	else 
		array_push($eq,$item);
}

$query="SELECT class_id, P_Class.value AS levels, name FROM `P_Class` INNER JOIN Class ON Class.class_id=P_Class.class_id WHERE player_id=".$_GET['pid'];
$res=mysql_query($query);
echo mysql_error();

while ($item=mysql_fetch_assoc($res)){
	$levels.=$item['name']." ".$item['levels']." ";
	switch  
}

$query="SELECT Skill.skill_id, player_id, name, base, value FROM Skill LEFT JOIN P_Skill ON Skill.skill_id=P_Skill.skill_id WHERE untrained=1 AND (player_id=".$_GET['pid']." OR player_id IS NULL) ORDER BY skill_id";
$res=mysql_query($query);
echo mysql_error();

$skills=array();
while ($item=mysql_fetch_assoc($res)){
	$skill=array();
	$skill['name']=$item['name'];
	$skill['base']=$item['base'];
	$skill['value']=$item['value'];
	array_push($skills, $skill);
}

$query="SELECT level, name, `desc`, school, components, `time`, `range`, target, duration, save, spell_resistance, phb, level FROM `P_Spell` INNER JOIN Spell ON P_Spell.spell_id=Spell.spell_id WHERE player_id=".intval($_GET['pid']);
$res=mysql_query($query);
echo mysql_error();

$spells=array();
while ($item=mysql_fetch_assoc($res)){
	array_push($spells, $item);
}



$bab[0]=$base['bab']+$att_bonus[$base['str']]; //base attack bonus [melee,proj]
$bab[1]=$base['bab']+$att_bonus[$base['dex']];

$next_level=array(0,1000,3000,6000,10000,15000,21000,28000,36000,45000,55000,66000,78000,91000);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>Dice Machine - Character sheet</title>
	<link rel="stylesheet" type="text/css" href="style.css" />
	<link type="text/css" href="css/ui-lightness/jquery-ui-1.8rc3.custom.css" rel="stylesheet" />	
	<link rel="stylesheet" type="text/css" href="js/mbtooltip/css/mbTooltip.css" title="style1"  media="screen">
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>          
	<script type="text/javascript" src="js/jquery-ui-1.8rc3.custom.min.js"></script>
	<script type="text/javascript" src="js/mbtooltip/inc/jquery.timers.js"></script>
	<script type="text/javascript" src="js/mbtooltip/inc/jquery.dropshadow.js"></script>
	<script type="text/javascript" src="js/mbtooltip/inc/mbTooltip.js"></script>
	
 	<script type="text/javascript">                                         
	<?php echo "var user_id=".intval($_GET["pid"]).";"?>
		var last_msg=0;
		var max_hp=<?php echo $base['hp']?>;
		var mode=0; 
		$(document).ready(function(){
			$("[title]").mbTooltip({
    			opacity : .90, //opacity
    			wait:1, //before show
    			ancor:"parent", //"parent"
    			cssClass:"default", // default = default
    			timePerWord:200, //time to show in milliseconds per word
    			hasArrow:false,
    			color:"white",
    			imgPath:"images/",
    			shadowColor:"black",
    			fade:1
  			});
			
			
			$(".spell_cast").click(function(){
				var roll='';
				var msg='';
				var dice=$(this).parent().prev().children(':first').val();
				if (dice!='Dice'){
					dice=dice.split('|');
					var len=dice.length;
					for (var i=0; i<len; i++){
						roll=roll+','+roll_dice(dice[i]);
						msg=msg+','+dice[i];
					}
					roll=roll.substr(1);
					msg='('+msg.substr(1)+')';
				};
				message={
						message: "<?php echo $base['p_name']; ?> casted <b>"+$(this).parent().prev().prev().children(':first').html()+"</b><br/>Rolls: "+roll+" "+msg,
						sender: user_id,
						receiver: 4,
				};
				
				$.post("save_message.php", message);
				
				message={
						message: "<?php echo $base['p_name']; ?> casted <b>"+$(this).parent().prev().prev().children(':first').html()+"</b>",
						sender: user_id,
						receiver: 0,
				};
				$.post("save_message.php", message);
				
			});
			
			$(".reg_roll").click(function(){
				var result;
				var value=$(this).parent().prev().html();
				var randNbr=Math.floor(Math.random()*20)+1;
				if (randNbr==20){result="Critical!";}
				else if (randNbr==1){result="Fumble!";}
				else{
					result=Number(randNbr)+Number(value);
				}
				$(this).parent().next().html(result);
				
				message={
						message: "<?php echo $base['p_name']; ?> threw <b>"+result+"</b> for <b>"+$(this).parent().parent().children(".attr_name").html()+"</b>",
						sender: user_id,
						receiver: 4,
				}
				$.post("save_message.php", message);
				if (mode==0){
					message.receiver=0;
					$.post("save_message.php", message);
				}
				
				set_mode('normal');
				
			});
			$(".attack_roll").click(function(){
				var result;
				var value=$(this).parent().prev().html();
				var threat=$(this).parent().prev().prev().prev().html();
				//var threat=10;
				var multiplier=$(this).parent().prev().prev().html();
				var randNbr=Math.floor(Math.random()*20)+1;
				
				if (randNbr>=threat){
					result="Threat "+(Number(randNbr)+Number(value));
					if (randNbr==20){result="Critical!";}
				}
				else if (randNbr==1){result="Fumble!";}
				else{
					result=Number(randNbr)+Number(value);
				}
				$(this).parent().next().html(result);
				
				message={
						message: "<?php echo $base['p_name']; ?> threw <b>"+result+"</b> for <b>"+$(this).parent().parent().children(".attr_name").html()+"</b>",
						sender: user_id,
						receiver: 4,
				}
				$.post("save_message.php", message);
				
				message.receiver=0;
				$.post("save_message.php", message);
				
				
			});
			
			$(".dmg_roll").click(function(){
				var roll=roll_dice($(this).html());
				message={
						message: "<?php echo $base['p_name']; ?> rolled <b>"+roll+"</b> for damage.",
						sender: user_id,
						receiver: 4,
				}
				$.post("save_message.php", message);
				message.receiver=0;
				$.post("save_message.php", message);
				$(this).parent().parent().children(".medium").html(roll+"(dmg)");
			});
			
			$(".chatlink").toggle(function(){ 
				$("div#"+$(this).attr('id')).fadeIn();
			}, function(){
				$("div#"+$(this).attr('id')).fadeOut();
			});
			
			$(".chatwrite").keypress(function(event){ //triggers on Enter
				if (event.keyCode==13){
					//write_to_chat_box($(this).prev(),$(this).val());
					message={
						message: $(this).val(),
						sender: user_id,
						receiver: $(this).parent().attr("id"),
					}
					$(this).val("");		
					$.post("save_message.php", message);
				}	
			});
			$(".chatlink").each(function(){
				var left_offset=$(this).parent().position().left;
				$("div#"+$(this).attr('id'))
					.offset({left: left_offset});
			});
			
			$('input.spell_input').focus(function(){
				$(this).removeClass('spell_input');
				if ($(this).attr('value')=='Dice')
					$(this).attr('value', '');
			});
			$('input.spell_input').blur(function(){
				if ($(this).attr('value')==''){
					$(this).attr('value', 'Dice');
					$(this).addClass('spell_input');
				}
			});
			
			load_messages();
			setInterval(load_messages, 3000);		
		});
		
		function load_messages(){
			
			$.post(	"load_messages.php", 
					{user_id: user_id, last_msg: last_msg}, 
					function(data){
						$.each(data, function(index, value){
							last_msg=value.message_id;
							if (value.type!=1){
								
								if(value.type==2){//damage
									$("<div title='Damage received'>You've just been hit! Your HP has been decreased by "+value.message+" points</div>").dialog();
									var new_hp=parseInt($("#curr_hp").html())-parseInt(value.message);
									if (new_hp>max_hp)
										new_hp=max_hp;
									if (new_hp<1){
										message={
											message: "",
											sender: user_id,
											receiver: 0,
										}
										if (new_hp==0)
											message.message= "<?php echo $base['p_name']; ?>"+" is disabled!";
										else if (new_hp<0 && new_hp>-10)
											message.message= "<?php echo $base['p_name']; ?>"+" is unconscious and bleeding to death!";
										else
											message.message= "<?php echo $base['p_name']; ?>"+" is dead!";
										
										$.post("save_message.php", message);
									}
									$("#curr_hp").html(new_hp);
								}
								else if(value.type==3){ //private roll
									set_mode('private');

								}
							}
							else{								
								if (value.receiver==0){
									var text="<span class=\"name\">"+value.p_name+"</span><span class=\"time\">"+value.time+"</span>"+value.message;
									write_to_chat_box($("div#NULL").children('.chattext'), text);
								}
								else{
									var text="<span class=\"time\">"+value.time+"</span>"+value.message;
									write_to_chat_box($("div#"+value.sender).children('.chattext'), text);
								}
								if (value.sender==user_id){
									var text="<span class=\"time\">"+value.time+"</span>"+value.message;
									write_to_chat_box($("div#"+value.receiver).children('.chattext'), text);
								}
							}
						});
					}, 
					"json");
		}   
		function write_to_chat_box(chatbox, text){
			chatbox=$(chatbox);
			chatbox.parent().fadeIn();
			chatbox.append(text+"<br/>");
			chatbox.animate({ //moves the div-scroller to bottom
				scrollTop: chatbox.attr("scrollHeight") - chatbox.height() 
						}
			, 100);
			
		}
		function set_mode(name){
			switch(name){
				case "normal": mode=0; $("#privateroll").fadeOut(); break;
				case "private": mode=1; $("#privateroll").fadeIn(); break;
			}
		}
		
		function roll_dice(dice){
			var bonus=dice.split('+');
			var dice=bonus[0].split('d');
			var roll=0;
			for (i=0;i<Number(dice[0]);i++){
				roll=roll+Math.floor(Math.random()*Number(dice[1]))+1;
				console.log(roll);
			}
			if (bonus=Number(bonus[1]))
				return roll+bonus;
			else
				return roll;
		}
 	</script> 
</head>

<body>
<div class="chatbox" id="2"> 
	<div class="chattext small"> </div>
	<input class="chatwrite"/>
</div>
<div class="chatbox" id="3"> 
	<div class="chattext small"> </div>
	<input class="chatwrite"/>
</div>
<div class="chatbox" id="4"> 
	<div class="chattext small"> </div>
	<input class="chatwrite"/>
</div>
<div class="chatbox pastebin" id="NULL"> 
	<div class="chattext small pastebin"> </div>
	<input class="chatwrite"/>
</div>
<div class="chatbar bold small">
	<div class="chatwrapper"><span class="chatlink" id="2">Hallu</span></div>
	<div class="chatwrapper"><span class="chatlink" id="3">Pette</span></div>
	<div class="chatwrapper"><span class="chatlink" id="4">Sanqu</span></div>
	<div class="chatwrapper"><span class="chatlink" id="NULL">Pastebin</span></div>
</div>
<div id="hitpoints" class="big">HP <span id="curr_hp"><?php echo $base["hp"]?></span>/<?php echo $base["hp"]?></div>
<div id="privateroll"><img src="pics/icons/6772avatar11.jpg"/></div>

<div id="mainContainer">

<div id="header" class="container">
	<div class="leftCol">
		<table>
			<tr>
				<td class="leftHeader bold">Name:</td>
				<td id="charName" class="input"><?php echo $base["c_name"]?></td>
			</tr>
			<tr>
				<td class="leftHeader bold">Race:</td>
				<td id="charName" class="input"><?php echo $base["race"]?></td>
			</tr>
			<tr>
				<td class="leftHeader bold">Alignment:</td>
				<td id="charName" class="input"><?php echo $base["align"]?></td>
			</tr>
			<tr>
				<td class="leftHeader bold">Religion:</td>
				<td id="charName" class="input"><?php echo $base["relig"]?></td>
			</tr>
		</table>
	</div>
	<div class="rightCol">
		<table>
			<tr>
				<td class="rightHeader bold">Class:</td>
				<td class="input"><?php echo $levels?></td>
			</tr>
			<tr>
				<td class="rightHeader bold">Level:</td>
				<td class="input"><?php echo $base["lvl"]?></td>
			</tr>
			<tr>
				<td class="rightHeader bold">Experience:</td>
				<td class="input"><?php echo $base["exp"];?></td>
			</tr>
			<tr>
				<td class="rightHeader bold">Next level:</td>
				<td class="input"><?php echo $next_level[$base["lvl"]];?></td>
			</tr>
		</table>
	</div>
</div>
<br/>
<div id="midSection" class="container">
	<div class="leftCol" id="stats">
		<table>
			<thead >
				<td class="bold veryBig">Stats</td>
				<td class="small">base</td>
				<td class="small">modifier</td>
				<td></td>
				<td class="small">result</td>
			</thead>
			<tr>
				<td class="stats_desc big bold attr_name">Strength</td>
				<td class="stats_val bold"><?php echo $base["str"]?></td>
				<td class="stats_val"><?php echo $att_bonus[$base["str"]]?></td>
				<td class="stats_roll"><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="stats_desc big bold attr_name">Dexterity</td>
				<td class="stats_val bold"><?php echo $base["dex"]?></td>
				<td class="stats_val"><?php echo $att_bonus[$base["dex"]]?></td>
				<td class="stats_roll"><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="stats_desc big bold attr_name">Constitution</td>
				<td class="stats_val bold"><?php echo $base["con"]?></td>
				<td class="stats_val"><?php echo $att_bonus[$base["con"]]?></td>
				<td class="stats_roll"><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="stats_desc big bold  attr_name">Intelligence</td>
				<td class="stats_val bold"><?php echo $base["int"]?></td>
				<td class="stats_val"><?php echo $att_bonus[$base["int"]]?></td>
				<td class="stats_roll"><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="stats_desc big bold attr_name">Wisdom</td>
				<td class="stats_val bold"><?php echo $base["wis"]?></td>
				<td class="stats_val"><?php echo $att_bonus[$base["wis"]]?></td>
				<td class="stats_roll"><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="stats_desc bold big attr_name">Charisma</td>
				<td class="stats_val bold"><?php echo $base["cha"]?></td>
				<td class="stats_val"><?php echo $att_bonus[$base["cha"]]?></td>
				<td class="stats_roll"><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
		</table>
	</div>
	<div class="rightCol" id="saves">
		<table>
			<thead>
				<td class="veryBig bold name">Saves</td>
				<td class="small">base</td>
				<td class="small">ability</td>
				<td class="small">magic</td>
				<td class="small">misc</td>
				<td class="small bold">total</td>
				<td></td>
				<td></td>
			</thead>
			<tr>
				<td class="bold attr_name">Fortitude save</td>
				<td><?php echo $base["fort_save"]; $fort_tot=$base["fort_save"]; ?></td>
				<td><?php echo $att_bonus[$base["con"]]; $fort_tot=$fort_tot+$att_bonus[$base["con"]]?></td>
				<td></td>
				<td></td>
				<td class="bold"><?php echo $fort_tot; ?></td>
				<td><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="bold attr_name">Will save</td>
				<td><?php echo $base["will_save"]; $will_tot=$bas["will_save"];?></td>
				<td><?php echo $att_bonus[$base["wis"]]; $will_tot=$will_tot+$att_bonus[$base["wis"]]?></td>
				<td></td>
				<td></td>
				<td class="bold"><?php echo $will_tot ?></td>
				<td><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="bold attr_name">Reflex save</td>
				<td><?php echo $base["ref_save"]; $ref_tot=$base["ref_save"]?></td>
				<td><?php echo $att_bonus[$base["dex"]]; $ref_tot=$ref_tot+$att_bonus[$base["dex"]]?></td>
				<td></td>
				<td></td>
				<td class="bold"><?php echo $ref_tot ?></td>
				<td><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td class="bold attr_name">Iniative</td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td class="bold"><?php echo $att_bonus[$base["dex"]]; $ref_tot=$ref_tot+$att_bonus[$base["dex"]]?></td>
				<td><button class="reg_roll">Roll</button></td>
				<td></td>
			</tr>
			<tr>
				<td>&nbsp;</td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
			</tr><!--
			<tr><td>&nbsp;</td></tr>
			<tr><td>&nbsp;</td></tr>-->
		</table>
	</div>

</div>
<br/>
<div class="container" id="midSection2">
	<div class="leftCol" style="width:420px">
		<table>
			<thead><td colspan="5" class="veryBig bold">Armor Class</td></thead>
			<tr>
				<td class="small bold">AC total</td>
				<td class="small">&nbsp;</td>
				<td class="small">armor</td>
				<td class="small">shield</td>
				<td class="small">dex</td>
				<td class="small">size</td>
				<td class="small">natural</td>
				<td></td>
				<td></td>
			</tr>
			<tr>
				<td class="bold">15</td>
				<td></td>
				<td>3</td>
				<td>0</td>
				<td>3</td>
				<td>1</td>
				<td>0</td>
				<td></td>
				<td></td>
				<td></td>
			</tr>
			<tr><td colspan="10">&nbsp;</td></tr>
			<tr>
				<td colspan="5" class="bold medium">Flatfooted AC:</td>
				<td class="bold">15</td>
			</tr>
			<tr>
				<td colspan="5" class="bold medium">No armor AC:</td>
				<td class="bold">12</td>
			</tr>
		</table>
	</div>
	<div class="leftCol" style="width:520px">
		<table style="font-size:small">
			<thead><td colspan="4" class="veryBig bold">Base Attack Bonus</td><td>&nbsp;</td><td class="big bold"><?php echo $bab[0]."/".$bab[1];?> </td></thead>
			<tr class="small">
				<td class='name bold small_pad'>weapon</td>
				<td class='small_pad tbl_align_ctr'>damage</td>
				<td class='small_pad tbl_align_ctr'>critical</td>
				<td class='small_pad tbl_align_ctr'>multiplier</td>
				<td class='bold small_pad tbl_align_ctr'>bonus</td>
				
			</tr>
			
				<?php
				foreach ($weapons as $item){
					$stats=explode('/', $item['value']);
					
					echo "<tr><td class='bold attr_name small_pad'>".$item['name']."</td>";
					echo "<td class='tbl_align_ctr'><button class='dmg_roll'>".$stats[0];
					if ($item['damagebonus']) {echo "+".$item['damagebonus'];}
					echo "</button></td>";
					echo "<td class='small_pad tbl_align_ctr'>".$stats[1]."</td>";
					echo "<td class='small_pad tbl_align_ctr'>".$stats[2]."</td>";
					echo "<td class='bold small_pad tbl_align_ctr'>".$item['hitbonus']."</td>";
					echo "<td><button class='attack_roll small_pad'>Roll</button></td>";
					echo "<td class='medium	x bold tbl_align_ctr'></td></tr>";
				}
				?>
			
			
		</table>
	</div>
</div>
<br/>
<div id="footer" class="container">
	<div class="leftCol">
		<table style="font-size: small;">
			<thead>
				<td colspan="5" class="veryBig bold">Skills</td>
			</thead>
			<tr>
				<td class="small name">skill name</td>
				<td class="small">base</td>
				<td class="small">modifier</td>
				<td class="small">skill</td>
				<td class="small">magic</td>
				<td class="small bold">total</td>
				<td></td>
				<td class="small">roll</td>
			</tr>
			<?php
			foreach ($skills as $skill){	
				echo "<tr><td class=\"attr_name bold\">".$skill["name"]."</td>\n";
				echo "<td>".$skill["base"]."</td>\n";
				echo "<td>".$att_bonus[$base[$skill["base"]]]."</td>\n";
				echo "<td>".$skill["value"]."</td>\n";
				echo "<td></td>\n";
				echo "<td class=\"bold\">";
				echo (intval($skill["value"])+intval($att_bonus[$base[$skill["base"]]]))."</td>\n";
				echo "<td><button class=\"reg_roll\">Roll</button></td>\n";
				echo "<td></td></tr>\n";
			}
			?>			
		</table>
	</div>
	<div class="rightCol">
		<table style="font-size: small;">
			<thead>
				<td colspan="5" class="veryBig bold">Spells</td>
			</thead>
		<?php
		$spell_level=-1;
		foreach($spells as $spell){
			
			if ($spell_level!=intval($spell['level'])){
				echo '<tr><td colspan="5" class="bold" style="padding: 5px 0 5px 30%;">Level '.$spell['level'].' spells</td></tr>';
				$spell_level=intval($spell['level']);
			}
			echo '<tr><td><input type="checkbox"/></td><td><span class="spell_item attr_name bold"><span class="spell_desc" title="<table><tr><td>Level:</td><td>'.$spell['level'].'</td></tr><tr><td>Description:</td><td>'.$spell['desc'].'</td></tr><tr><td>School:</td><td>'.$spell['school'].'</td></tr><tr><td>Components:</td><td>'.$spell['components'].'</td></tr><tr><td>Time:</td><td>'.$spell['time'].'</td></tr><tr><td>Range:</td><td>'.$spell['range'].'</td></tr><tr><td>Target/type:</td><td>'.$spell['target'].'</td></tr><tr><td>Duration:</td><td>'.$spell['duration'].'</td></tr><tr><td>Save:</td><td>'.$spell['save'].'</td></tr><tr><td>Spell resistance:</td><td>'.$spell['spell_resistance'].'</td></tr><tr><td>PHB Page:</td><td>'.$spell['phb'].'</td></tr></table>">'.$spell['name'].'</span></span></td><td><input class="spell_input" type="text" size="10" value="Dice"/></td><td><button class="spell_cast">Cast</button></td><td></td></tr>';
		}
		?>
		</table>
	</div>
</div>
<br/>&nbsp;
<br/>&nbsp;
<br/>.   
</div>
</body>
</html>
